var jForest = jForest || {};
var jf = jForest;

(function($,undefined){
jForest.TreeNode = function(options){
	this.options = $.extend({
		id:null,
		pid:null,
		name:null,
		href:null,
		icon:null,
		checked:false,
		isLeaf:true
	},options);
	
	this._isLoad = false;
	this._isOpen = false;
	this._isLast = true;
	this._isFirst = false;
	this._depth = [];
}

jForest.TreeNode.prototype = {
	_createEl:function(tree,pNode){
		var opt = this.options,tOpt = tree.options,node = this;
		
		if(pNode == null){this._isFirst = true;}else{
			for(var i=0;i<pNode._depth.length;i++){
				this._depth.push(pNode._depth[i]);
			}
			if(pNode._isLast){this._depth.push(1);}else{this._depth.push(0);}
		}
		var str = '<div class="dTreeNode tn-'+opt.id+'">';
		//缩进
		for(var i=0;i<this._depth.length;i++){
			if(this._depth[i] == 1){
				str += '<img class="lv-'+i+'" src="'+tOpt.iconPath + tOpt.icon.empty+'" alt="" />';
			}else{
				str += '<img class="lv-'+i+'" src="'+tOpt.iconPath + tOpt.icon.line+'" alt="" />';
			}
		}
		if(opt.isLeaf == true){
			if(this._isFirst == true){
				str += '<img class="lv-'+i+'" src="'+tOpt.iconPath + tOpt.icon.empty+'" alt="" />';
			}else if(this._isLast == true){
				str += '<img class="tree-join" src="'+tOpt.iconPath + tOpt.icon.joinBottom+'" alt="" />';
			}else{
				str += '<img class="tree-join" src="'+tOpt.iconPath + tOpt.icon.join+'" alt="" />';
			}
			if(tOpt.checkbox == true){
				str += '<input type="checkbox" value="'+opt.id+'" style="vertical-align:middle;margin:0;"/>';
			}
			//图标
			str += '<img class="tree-icon" src="'+tOpt.iconPath + tOpt.icon.node+'" alt="" />';
		}else{
			if(this._isFirst == true){
				str += '<a class="tree-join" href="#'+opt.id+'" jf-fun="treeJoinClick" jf-data-status="0"><img src="'+tOpt.iconPath + tOpt.icon.nlPlus+'" alt="" /></a>';
			}else if(this._isLast == true){
				str += '<a class="tree-join" href="#'+opt.id+'" jf-fun="treeJoinClick" jf-data-status="0"><img class="tree-join" src="'+tOpt.iconPath + tOpt.icon.plusBottom+'" alt="" /></a>';
			}else{
				str += '<a class="tree-join" href="#'+opt.id+'" jf-fun="treeJoinClick" jf-data-status="0"><img class="tree-join" src="'+tOpt.iconPath + tOpt.icon.plus+'" alt="" /></a>';
			}
			if(tOpt.checkbox == true){
				str += '<input type="checkbox" value="'+opt.id+'" style="vertical-align:middle;margin:0;"/>';
			}
			//图标
			str += '<img class="tree-icon" src="'+tOpt.iconPath + tOpt.icon.folder+'" alt="" />';
		}
		//节点
		str += '<a class="node" href="javascript:void(0);">' +  opt.name + '</a></div>';
		
		this.$el = $(str).data('id',opt.id);
		
		this.$el.find('.node').click(function(){
			tOpt.nodeClick.apply(tree,[node]);
		});
		this.$el.find('[jf-fun="treeJoinClick"]').click(function(){
			if(node._isOpen == true){
				node.close(tree);
			}else if(node._isLoad == false){
				tree.loadData(node);
			}else{
				node.open(tree);
			}
		});
		if(tOpt.checkbox == true){
			this.$el.find('>input[type="checkbox"]')[0].checked = opt.checked;
			if(pNode){
				if(opt.checked == true){
					pNode.$el.find('>input[type="checkbox"]')[0].checked = true;
				}else{
					this.$el.find('>input[type="checkbox"]')[0].checked = pNode.$el.find('>input[type="checkbox"]')[0].checked;
				}
			}
		}
		this.$el.find('>input[type="checkbox"]').click(function(){
			var checkbox = this;
			tree.options.checkboxClick.apply(tree,[node,checkbox.checked]);
			node.$el.find('.clip input[type="checkbox"]').each(function(i,el){
				el.checked = checkbox.checked;
				var childNode = tree.nodes[$(el).val()];
				if(childNode){
					tree.options.checkboxClick.apply(tree,[childNode,checkbox.checked]);
				}
			});
		});
		return this.$el;
	},
	addChild:function(tree,node){
		var ops = this.options; tOps = tree.options;
		if(ops.isLeaf == true){
			ops.isLeaf = false;
			//修改连接
			if(this._isFirst == true){
				this.$el.find('>.tree-join').attr('src',tOps.iconPath + tOps.icon.nlPlus).wrap('<a href="#'+ops.id+'" jf-fun="treeJoinClick" jf-data-status="0"></a>');
			}else if(this._isLast == true){
				this.$el.find('>.tree-join').attr('src',tOps.iconPath + tOps.icon.plusBottom).wrap('<a href="#'+ops.id+'" jf-fun="treeJoinClick" jf-data-status="0"></a>');
			}else{
				this.$el.find('>.tree-join').attr('src',tOps.iconPath + tOps.icon.plus).wrap('<a href="#'+ops.id+'" jf-fun="treeJoinClick" jf-data-status="0"></a>');
			}
			//修改图标
			this.$el.find('>.tree-icon').attr('src',tOps.iconPath + tOps.icon.folder);
		}
		if(this.$el.find('.tc-'+ops.id).length == 0){this.$el.append('<div class="clip tc-'+ops.id+'" style="display:none;"></div>');}
		var temp = this.$el.find('.tc-'+ops.id+'>.dTreeNode:last');
		if(temp.length == 1){
			var id = temp.data('id');
			var tempNode = tree.nodes[id];
			tempNode._isLast = false;
			if(tempNode.options.isLeaf == true){
				tempNode.$el.find('.tree-join').attr('src',tOps.iconPath + tOps.icon.join);
			}else{
				tempNode.$el.find('.tree-join').attr('src',tOps.iconPath + tOps.icon.plus);
			}
		}
		this.$el.find('.tc-'+ops.id).append(node._createEl(tree,this));
	},
	clear:function(){
		this.$el.find('>.clip').empty();
		var checkbox = this.$el.find('>input[type="checkbox"]');
		if(checkbox[0]){checkbox[0].checked = false;}
	},
	open:function(tree){
		this.$el.find('>.tree-icon').attr('src',tree.options.iconPath + tree.options.icon.folderOpen);
		if(this._isFirst == true){
			this.$el.find('>.tree-join img').attr('src',tree.options.iconPath + tree.options.icon.nlMinus);
		}if(this._isLast == true){
			this.$el.find('>.tree-join img').attr('src',tree.options.iconPath + tree.options.icon.minusBottom);
		}else{
			this.$el.find('>.tree-join img').attr('src',tree.options.iconPath + tree.options.icon.minus);
		}
		this._isOpen = true;
		this.$el.find('>div').show();
	},
	close:function(tree){
		this.$el.find('>.tree-icon').attr('src',tree.options.iconPath + tree.options.icon.folder);
		if(this._isFirst == true){
			this.$el.find('>.tree-join img').attr('src',tree.options.iconPath + tree.options.icon.nlPlus);
		}else if(this._isLast == true){
			this.$el.find('>.tree-join img').attr('src',tree.options.iconPath + tree.options.icon.plusBottom);
		}else{
			this.$el.find('>.tree-join img').attr('src',tree.options.iconPath + tree.options.icon.plus);
		}
		this._isOpen = false;
		this.$el.find('>div').hide();
	}
}
	
})(window.jQuery);

(function($){
	var KEY = "jforest.tree";
	
	var Tree = function(element,options){
		this.$el = $(element);
		this.nodes = {};
		
		this.ajax = $.extend({
			url:null,
			dataType:'json',
			dataFormat:function(node){
				return {
					pid:node.options.id
				};
			},
			callback:function(result){
				return result;
			}
		},options.ajax);
		
		delete options.ajax;
		
		//创建根目录
    	this.root =  new jForest.TreeNode($.extend({
			id:null,
    		pid:null,
			isLeaf:false,
    		name:'根节点'
		},options.root));
		
		this.root._isLast = true;
		
		delete options.root;
		
    	this.options = $.extend({
    		nodeClick:function(node){},
			checkboxClick:function(node){return true;},
			autoLoad:true,
			checkbox:false,
    		iconPath:'assets/jforest/images/tree/',
    		icon:{
    			root:'base.gif',
    			empty:'empty.gif',
    			line:'line.gif',
    			join:'join.gif',
				joinBottom:'joinbottom.gif',
				plus:'plus.gif',
				plusBottom:'plusbottom.gif',
				minus:'minus.gif',
				minusBottom:'minusbottom.gif',
				nlPlus:'nolines_plus.gif',
				nlMinus:'nolines_minus.gif',
				node:'page.gif',
				folder:'folder.gif',
				folderOpen:'folderopen.gif'
    		}
    	}, options);
		
    	//给容器添加样式
    	this.$el.addClass('dtree');
		this.$el.append(this.root._createEl(this,null));
		if(this.options.autoLoad == true){
			this.loadData(this.root);
		}
	};
	
	Tree.prototype = {
		addNode:function(item){
			var node = new jForest.TreeNode(item);
			var pNode = this.nodes[node.options.pid] || this.root;
			pNode.addChild(this,node);
			this.nodes[node.options.id] = node;
		},
		loadData:function(node){
			var tree = this;
			if(this.ajax.url){
				$.getJSON(this.ajax.url,this.ajax.dataFormat(node),function(result){
					var nodes = tree.ajax.callback(result,node);
					if($.isArray(nodes)){
						node.clear();
						for(var i=0;i<nodes.length;i++){
							var child = $.extend({
								pid:node.options.id
							},nodes[i]);
							
							tree.addNode(child);
						}
						node._isLoad = true;
					}
					node.open(tree);
				});
			}else{
				node.open(tree);
			}
		},
		rootLoadData:function(){
			this.loadData(this.root);
		},
		updateNode:function(options){
			var node = this.nodes[options.id];
			if(node){
				node.name = options.name;
				$('.tn-'+options.id+'>.node').html(options.name);
			}
		},
		updateRoot:function(options){
			$.extend(this.root.options,options);
			this.root.$el.find('>.node').html(this.root.options.name);
		},
		refreshLoad:function(nodeId){
			var node = this.nodes[nodeId];
			if(node){
				node._isLoad = false;
				node.clear();
				node.close(this);
			}else if(nodeId == this.root.options.id){
				this.root._isLoad = false;
				this.root.clear();
				this.root.close(this);
			}
		},
		refreshRoot:function(){
			this.root._isLoad = false;
			this.root.clear();
			this.root.close(this);
		}
	};

	$.fn.jfTree = function(){
		var args = Array.prototype.slice.call(arguments, 0);
		var value = undefined;
		this.each(function () {
			var $this = $(this);
			if (args.length === 0 || typeof(args[0]) === "object") {
				opts = args.length === 0 ? {} : $.extend({}, args[0]);
				$this.data(KEY,new Tree(this,opts)); //创建控件
			}else if (typeof(args[0]) === "string"){
				var entity = $this.data(KEY);
                if(entity === undefined){return;}
                value = entity[args[0]].apply(entity, args.slice(1));
			}else{
				 throw 'Invalid arguments to '+KEY+' plugin: ' + args;
			}
	    });
	    return (value === undefined) ? this : value;
	};
	
	$.fn.jfTree.Constructor = Tree;
})(window.jQuery)